package com.dapeis.web.wx.controller.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ag.core.exception.InvalidParamException;
import com.ag.core.exception.SysTipsException;
import com.ag.core.utils.AgAssert;
import com.ag.utils.DateUtils;
import com.ag.utils.DictionarySettingUtils;
import com.ag.utils.NumberUtils;
import com.ag.utils.json.AGsonBuilder;
import com.dapeis.core.utils.DBConfigUtils;
import com.dapeis.core.utils.RequirementConfig;
import com.dapeis.domain.Coupons;
import com.dapeis.domain.Order;
import com.dapeis.domain.Requirement;
import com.dapeis.domain.Shop;
import com.dapeis.service.CouponsService;
import com.dapeis.service.OrderService;
import com.dapeis.service.RequirementService;
import com.dapeis.service.ShopService;
import com.dapeis.web.wx.controller.IRequirementController;
import com.dapeis.web.wx.controller.RestController;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

@Controller
@RequestMapping("/wx/requirement")
public class RequirementController extends RestController implements
	IRequirementController {

    @Resource
    RequirementService requirementService;

    @Resource
    OrderService orderService;

    @Resource
    CouponsService couponsService;

    @Resource
    ShopService shopService;

    /**
     * 咨询
     */
    public @ResponseBody JsonElement addConsulting(
	    @RequestParam(required = false) Integer shopId,
	    @RequestParam String[] scene, @RequestParam String[] garderobe_ids,
	    @RequestParam String[] shop, @RequestParam String sex,
	    @RequestParam String costCode, @RequestParam String remark,
	    HttpServletRequest request) {
	if (null != scene && scene.length >= 1 && null != shop
		&& shop.length >= 1 && null != garderobe_ids
		&& garderobe_ids.length >= 1 && StringUtils.isNotBlank(sex)
		&& StringUtils.isNotBlank(costCode)
		&& StringUtils.isNotBlank(remark)) {
	    return doSaveRequirement(shopId, RequirementConfig.Type.CONSULTING,
		    scene, shop, garderobe_ids, costCode, remark, sex, null,
		    null, null);
	}
	throw new InvalidParamException();
    }

    /**
     * 购物
     * 
     */

    public @ResponseBody JsonElement addBuy(
	    @RequestParam(required = false) Integer shopId,
	    @RequestParam String[] scene, @RequestParam String[] shop,
	    @RequestParam String sex, @RequestParam String costCode,
	    @RequestParam String remark, HttpServletRequest request) {
	if (null != scene && scene.length >= 1 && null != shop
		&& shop.length >= 1 && StringUtils.isNotBlank(sex)
		&& StringUtils.isNotBlank(costCode)
		&& StringUtils.isNotBlank(remark)) {
	    return doSaveRequirement(shopId, RequirementConfig.Type.BUY, scene,
		    shop, null, costCode, remark, sex, null, null, null);
	}
	throw new InvalidParamException();
    }

    /**
     * 陪逛
     */
    public @ResponseBody JsonElement addShopping(
	    @RequestParam(required = false) Integer shopId,
	    @RequestParam String[] scene, @RequestParam String[] shop,
	    @RequestParam String sex, @RequestParam String costCode,
	    @RequestParam String remark, @RequestParam String countyCode,
	    @RequestParam String addres, @RequestParam String time,
	    HttpServletRequest request) {
	if (null != scene && scene.length >= 1 && null != shop
		&& shop.length >= 1 && StringUtils.isNotBlank(sex)
		&& StringUtils.isNotBlank(costCode)
		&& StringUtils.isNotBlank(remark)
		&& StringUtils.isNotBlank(countyCode)
		&& StringUtils.isNotBlank(addres)
		&& StringUtils.isNotBlank(time)) {

	    return doSaveRequirement(shopId, RequirementConfig.Type.SHOPPING,
		    scene, shop, null, costCode, remark, sex, countyCode,
		    addres, time);
	}
	throw new InvalidParamException();
    }

    /**
     * 整理
     * 
     * @param remark
     * @param cityCode
     * @param addres
     * @param time
     * @param request
     * @return
     */

    public @ResponseBody JsonElement addFinishing(
	    @RequestParam(required = false) Integer shopId,
	    @RequestParam String remark, @RequestParam String countyCode,
	    @RequestParam String addres, @RequestParam String time,
	    HttpServletRequest request) {
	if (StringUtils.isNotBlank(remark)
		&& StringUtils.isNotBlank(countyCode)
		&& StringUtils.isNotBlank(addres)
		&& StringUtils.isNotBlank(time)) {

	    Requirement requirement = new Requirement();
	    requirement.setRemark(remark);
	    requirement.setType(RequirementConfig.Type.FINISHING);
	    requirement.setCreateTime(new Date().getTime() / 1000);

	    return doSaveRequirement(shopId, RequirementConfig.Type.FINISHING,
		    null, null, null, null, remark, null, countyCode, addres,
		    time);
	}
	throw new InvalidParamException();
    }

    public JsonElement doSaveRequirement(Integer shopId, Integer type,
	    String[] scene, String[] shop, String[] garderobe_ids,
	    String costCode, String remark, String sex, String countyCode,
	    String addres, String time) {
	Requirement requirement = new Requirement();
	if (type == RequirementConfig.Type.BUY
		|| type == RequirementConfig.Type.CONSULTING
		|| type == RequirementConfig.Type.SHOPPING) {
	    if (!checkParamSetting(scene, shop)) {
		throw new InvalidParamException("场景或商品Code不存在！");
	    }
	    String sceneCode = parser(scene);
	    String shopCode = parser(shop);
	    requirement.setCostCode(costCode);
	    requirement.setSceneCode(sceneCode);
	    requirement.setShop(shopCode);
	    requirement.setSex(new Integer(sex));

	    if (type == RequirementConfig.Type.CONSULTING) {
		String garderobeStr = parser(garderobe_ids);
		requirement.setGarderobe(garderobeStr);
	    }
	}
	if (type == RequirementConfig.Type.SHOPPING
		|| type == RequirementConfig.Type.FINISHING) {
	    requirement.setAddres(addres);
	    requirement.setCityCode(countyCode);
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm");
	    try {
		requirement.setTime(sdf.parse(time).getTime() / 1000);
	    } catch (ParseException e) {
		e.printStackTrace();
	    }
	}
	requirement.setRemark(remark);
	requirement.setUserId(getThreadLocalUserId());
	requirement.setType(type);
	requirement.setCreateTime(new Date().getTime() / 1000);
	if (NumberUtils.isValid(shopId)) {
	    Shop dpsShop = shopService.selectByPrimaryKey(shopId);
	    AgAssert.notNull(dpsShop, InvalidParamException.class, "无效的服务ID参数:"
		    + shopId);
	    AgAssert.isTrue(dpsShop.getType() == type, InvalidParamException.class, "服务类型异常!");
	    requirement.setShopId(shopId);
	}

	boolean result = requirementService.insert(requirement) > 0;

	if (result) {
	    JsonObject json = success();
	    Order order = orderService.createOrderRequirement(requirement,
		    getThreadLocalUser());
	    requirement.setOrderId(order.getId());
	    requirementService.updateByPrimaryKeySelective(requirement);
	    json.addProperty("orderId", order.getId().toString());
	    json.addProperty("type", requirement.getType().toString());
	    return json;
	}
	throw new SysTipsException("发布需求失败,请重试!");
    }

    /**
     * 解析数组，拼装
     * 
     * @param arr
     * @return
     */
    public String parser(String[] arr) {
	String str = "";
	if (null != arr && arr.length >= 1) {
	    for (String elemt : arr) {
		str += elemt + RequirementConfig.SPE_SUX;
	    }
	}
	return str;
    }

    /**
     * 获取需求价格
     * 
     * @param type
     * @return
     */
    public Integer getRequirementOriginalPrice(Integer type) {
	String initPrice = DictionarySettingUtils
		.getParameterValue(RequirementConfig.PRIC_INIT + "." + type);
	Integer price = new Integer(initPrice);
	return price;
    }

    /**
     * 检查前端传回来的参数是否已经配置
     * 
     * @return
     */
    public boolean checkParamSetting(String[] scene, String[] shop) {
	Map<String, String> cjMap = DictionarySettingUtils
		.getParameterMap(RequirementConfig.CHANG_JING_PRE);
	Map<String, String> shopMap = DictionarySettingUtils
		.getParameterMap(RequirementConfig.LADY_SHOP_CHOOSE);
	for (String sce_val : scene) {
	    boolean isContain = cjMap.containsKey(sce_val);
	    if (!isContain) {
		return false;
	    }
	}

	for (String sp_val : shop) {
	    boolean isContain = shopMap.containsKey(sp_val);
	    if (!isContain) {
		return false;
	    }

	}
	return true;
    }

    /**
     * 无业务关系，读取需求配置关系
     * 
     * @param request
     * @param response
     * @return
     */

    @RequestMapping("/config")
    public @ResponseBody JsonElement requirementConfig(
	    HttpServletRequest request) {

	JsonObject jsonObject = buildSuccess();

	Map<String, String> cjMap = DictionarySettingUtils
		.getParameterMap(RequirementConfig.CHANG_JING_PRE);
	String cjStr = "";
	for (Entry<String, String> entry : cjMap.entrySet()) {
	    cjStr += entry.getKey() + ":'" + entry.getValue() + "'";
	}

	Map<String, String> shopMap = DictionarySettingUtils
		.getParameterMap(RequirementConfig.LADY_SHOP_CHOOSE);
	String shopStr = "";
	for (Entry<String, String> entry : shopMap.entrySet()) {
	    shopStr += entry.getKey() + ":'" + entry.getValue() + "'";
	}

	jsonObject.addProperty("场景_scene", cjStr);
	jsonObject.addProperty("商品选择_shop", shopStr);

	return jsonObject;
    }

}
